﻿using System;
using System.Diagnostics;
using System.DirectoryServices;
using System.IO;
using CommandLineParser.Arguments;
using uTILLIty.ADExtractor.Core;
using uTILLIty.ADExtractor.Core.Exporters.Csv;
using uTILLIty.ADExtractor.Properties;

namespace uTILLIty.ADExtractor
{
	internal class CsvExportCommand : ExportCommandBase
	{
		[FileArgument('o', "output", FileMustExist = false, Optional = true,
			Description = "specify a filename", FullDescription = "leave blank, to export to the console", Example = "output.csv")]
		public FileInfo OutputFile;

		[ValueArgument(typeof(string), 'e', "encoding", Optional = true, DefaultValue = "",
			Description = "a valid encoding", FullDescription = "", Example = "-e UTF-8, Windows-1252, etc.")]
		public string Encoding;

		[ValueArgument(typeof(string), 's', "sep", Optional = true, DefaultValue = ";",
			Description = "the separator to use", FullDescription = "", Example = "-s ;")]
		public string Separator;

		[EnumeratedValueArgument(typeof(ValueEnquotationType), 'v', "venqot", Optional = true, DefaultValue = ValueEnquotationType.None,
			Description = "the type of value-enquotation to use", FullDescription = "", AllowedValues = "None,SingleQuotes,DoubleQuotes", Example = "-v {None|SingleQuotes|DoubleQuotes}")]
		public ValueEnquotationType ValueEnquotation;

		protected override bool OnBeforeRunQuery(QueryInformation query)
		{
			if (string.IsNullOrWhiteSpace(LdapUsername) || !String.IsNullOrWhiteSpace(LdapPassword))
				return true;

			if (OutputFile == null)
				throw new ApplicationException(Resources.SupplyPasswordInSwitchInNonInteractiveMode);
			
			return true;
		}

		public override string GetAdditionalHelpText()
		{
			FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(typeof(Program).Assembly.Location);
			return string.Format(Resources.SimpleUsageExample, Path.GetFileName(fileInfo.FileName),
													 "CSV -q \"(&(objectCategory=User)(initials=*))\" -f objectSID,displayName,Manager:manager.samAccountName,count(memberof)");
		}

		protected override bool Export(QueryInformation query, SearchResultCollection result)
		{
			var exporter = new CsvExporter();
			exporter.LogMessage += (o, e) => Console.WriteLine(Resources.LogMessageOutput, e.Severity, e.Message);

			var config = new CsvExporterConfiguration
			             	{
			             		Encoding = Encoding,
			             		OutputFilename = OutputFile != null ? OutputFile.FullName : null,
			             		Separator = Separator,
			             		ValueEnquotation = ValueEnquotation
			             	};
			exporter.Export(query, result, config);
			return true;
		}

	}
}